﻿using SSCAI.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace SSCAI.DAL
{
    public class XmlHelper
    {
        private static IEnumerable<XElement> missingItems = new List<XElement>();
        private static string latestIssue = string.Empty;
        private static string url = @"http://www.cqcp.net/ajaxhttp/game/getopennumber.aspx";
        private static string param = "?idMode=3002&iCount=";

        public static int LoopCount = 0;

        public static void GetDataFromWeb()
        {
            //this.AddMissingItems(url, param);
            UpdateAllData(30);
            //GetLatestIssue();
            //AddOneItem(url, param + "1");
        }

        public static IEnumerable<XElement> GetXmlItems()
        {
            return LoadXmlFile().Root.Descendants("item");
        }

        public static XDocument LoadXmlFile()
        {
            return XDocument.Load(GetXmlFile());
        }


        public static void GetLatestIssue()
        {
            latestIssue = LoadXmlFile().Root.Elements("item").FirstOrDefault().Attribute("issue").Value;
        }

        public static void UpdateAllData(int counts)
        {
            XDocument doc = LoadXmlFile();
            var em = doc.Root.Elements("item");
            em.Remove();
            doc.Save(GetXmlFile());

            string response = string.Empty;
            var iLoop = 0;

            for (int i = counts; i > 0; i--)
            {
                while (string.IsNullOrEmpty(response) && iLoop < 100)
                {
                    response = HttpHelper.Get(url, param + i.ToString(), null);
                    iLoop++;
                    Thread.Sleep(300);
                }

                if (null != response)
                {
                    var result = response.Split('|');
                    var xml = result[result.Length - 1].Replace("<br/>", ",");
                    AddItems(doc, xml);
                    response = string.Empty;
                    iLoop = 0;
                }

                LoopCount = counts - i;
            }
        }

        public static void GetMissingItems(string xml, out bool findFlag)
        {
            var items = GetItems(xml);
            var isExist = items.Where(i => i.Elements("li").Where(li => li.Value == latestIssue).FirstOrDefault() != null).FirstOrDefault();
            missingItems = missingItems.Concat(items);

            findFlag = isExist != null;
        }

        public static void AddMissingItems()
        {
            XDocument doc = LoadXmlFile();

            var response = string.Empty;
            var iLoop = 0;
            for (var i = 1; i < 100; i++)
            {
                while (string.IsNullOrEmpty(response) && iLoop < 100)
                {
                    response = HttpHelper.Get(url, param + i.ToString(), null);
                    Thread.Sleep(200);
                    iLoop++;
                }

                var result = response.Split('|');
                var xml = result[result.Length - 1].Replace("<br/>", ",");
                bool findFlag;

                GetMissingItems(xml, out findFlag);
                response = string.Empty;
                iLoop = 0;

                if (findFlag)
                {
                    break;
                }
            }

            missingItems = missingItems.Reverse();

            missingItems
                .Select(i =>
                {
                    var li = i.Elements("li").Select(l => new { value = l.Value }).ToList();
                    var issue = li[0].value;
                    var lottery = li[1].value.Replace("-", string.Empty);
                    var sum = li[2].value;
                    var isExist = doc.Root.Elements("item").Where(e => e.Attribute("issue").Value == issue).FirstOrDefault();
                    if (isExist == null)
                    {
                        doc.Root.AddFirst(CreateItem(issue, lottery, sum));
                    }

                    return i;
                }).ToList();

            doc.Save(GetXmlFile());
        }

        public static void AddItems(XDocument doc, string xml)
        {
            var items = GetItems(xml);
            items = items.Reverse();
            foreach (var item in items)
            {
                var li = item.Elements("li").Select(l => new { value = l.Value }).ToList();
                var issue = li[0].value;
                var lottery = li[1].value.Replace("-", string.Empty);
                var sum = li[2].value;
                doc.Root.AddFirst(CreateItem(issue, lottery, sum));
            }

            doc.Save(GetXmlFile());
        }

        public static void AddOneItem(out bool isAdded)
        {
            isAdded = false;
            string response = string.Empty;
            int iLoop = 0;

            while (string.IsNullOrEmpty(response) && iLoop < 100)
            {
                response = HttpHelper.Get(url, param + "1", null);
                Thread.Sleep(300);
                iLoop++;
            }

            if (null != response)
            {
                var result = response.Split('|');

                if (result == null || result.Length < 2)
                {
                    return;
                }

                XDocument doc = LoadXmlFile();
                var xml = result[result.Length - 1].Replace("<br/>", ",");
                var items = GetItems(xml).FirstOrDefault().Elements("li").Select(l => new { value = l.Value }).ToList();
                var issue = items[0].value;
                var lottery = items[1].value.Replace("-", string.Empty);
                var sum = items[2].value;
                var isExist = doc.Root.Elements("item").Where(i => i.Attribute("issue").Value == issue).FirstOrDefault();
                if (isExist == null)
                {
                    InsertLottery(doc, issue, lottery, sum);
                    isAdded = true;
                }
            }
        }

        public static IEnumerable<XElement> GetItems(string xml)
        {
            xml = string.Concat("<items>", xml, "</items>");
            XElement root = XElement.Parse(xml);
            return root.Elements("ul").Where(u => u.Element("li").Value.StartsWith("1"));
        }

        public static XElement GetItem(IEnumerable<XElement> items)
        {
            return items.FirstOrDefault();
        }

        public static string GetXmlFile()
        {
            return Path.Combine(Environment.CurrentDirectory, @"Resource\SSCData.xml");
        }

        public static void InsertLottery(XDocument doc, string issue, string lottery, string sum)
        {
            XElement item = CreateItem(issue, lottery, sum);
            doc.Root.AddFirst(item);
            doc.Save(GetXmlFile());
        }

        public static XElement CreateItem(string issue, string lottery, string sum)
        {
            return new XElement("item",
                new XAttribute("issue", issue),
                new XAttribute("lottery", lottery),
                new XAttribute("sum", sum),
                new XAttribute("time", DateTime.Now.ToString())
                );
        }

        public static string GetUserInfoXmlFile()
        {
            return Path.Combine(Environment.CurrentDirectory, @"Resource\userinfo.xml");
        }

        public static IEnumerable<XElement> GetUserInfoItems()
        {
            return XDocument.Load(GetUserInfoXmlFile()).Root.Descendants("user");
        }

        public static void UpdateUserInfo(string sn)
        {
            XDocument doc = XDocument.Load(GetUserInfoXmlFile());
            var em = doc.Root.Elements("user");
            em.Remove();
            doc.Save(GetUserInfoXmlFile());

            if (null != sn)
            {
                doc.Root.AddFirst(new XElement("user", new XAttribute("username", SSCAI.Common.CalculateHelper.GetUserName(sn)), new XAttribute("sn", sn)));
                doc.Save(GetUserInfoXmlFile());
            }
        }
    }
}
